<template>
  <div style="position: fixed; top: 0;z-index: 500;">
    <header class="headerTrans">
      <!--        <div class="headerBox">-->
      <router-link to="/">
        <img :src="icon" alt=""
             style="position: fixed; height: 8vh;width: 8vh; left: 8vh; top: 0.8vh; z-index: 60">
      </router-link>
      <!--        <img :src="titleImg" alt=" " height="75px" style="position: fixed; height: 75px; left: 150px">-->
      <el-menu
          :default-active="activeIndex"
          mode="horizontal"
          background-color="#00000000"
          :text-color="navColor"
          :active-text-color="navColor1"
          router
          default-active="/"
          class="el-menu1"
          style="color:#ffd04b !important;"
      >
        <el-menu-item index="/">首页</el-menu-item>
        <el-menu-item index="/journalList">期刊列表</el-menu-item>
<!--        <el-menu-item index="/category">分类浏览</el-menu-item>-->
        <!--        <el-menu-item index="/institute">机构</el-menu-item>-->

        <!--        <el-menu-item index="/help">帮助</el-menu-item>-->
        <!--        <el-menu-item index="/check">查重</el-menu-item>-->
        <!--        <el-menu-item index="/more">更多</el-menu-item>-->
      </el-menu>
      <!--        </div>-->
    </header>
    <!--      <div style="position: fixed; z-index: 60; right: 10vw;top: 3vh;margin-right: 3vw">-->
    <!--        &lt;!&ndash;      <router-link to="/login" style="margin-right: 2vw">&ndash;&gt;-->
    <!--        <el-button type="primary" @click="loginFormVisible=true">登录</el-button>-->
    <!--        &lt;!&ndash;      </router-link>&ndash;&gt;-->
    <!--        &lt;!&ndash;      <router-link to="/register" style="margin-right: 2vw">&ndash;&gt;-->
    <!--        <el-button type="success">注册</el-button>-->
    <!--        &lt;!&ndash;      </router-link>&ndash;&gt;-->
    <!--      </div>-->
    <!--    <a href="https://readpaper.com/help#tab=reading" style="position: fixed; z-index: 60; margin-left: 50vw;top: 2vh;">-->
    <!--      <h2>参考一下</h2></a>-->
    <md-input v-model="searchWord" autocomplete="off" id="navSearch" placeholder="搜索"
              style=" position: fixed; z-index: 60; right: 15vw;top: -0.2vh;" @keyup.enter.native="primarySearch">
      <span style="">随处搜索</span>
    </md-input>
    <el-input
        v-model="searchWord"
        id="navSearch1"
        placeholder="海量资源，等你发现"
        style=" position: fixed; width: 36vw; z-index: 60; right: 17vw;top: 2.1vh;"
        input-style="height: 6.5vh;border-radius: 1.5vw;"
        @keyup.enter="primarySearch"
        suffix-icon="Search"
    />
    <el-dropdown style="position: fixed; z-index: 60; right: 10vw;margin-top: 8vh; margin-right: 1vw"
                 :disabled="!this.isLogin">
      <el-avatar style="position: fixed; z-index: 60; right: 10vw;top: 3vh;" shape="square" size="large"
                 :style="{'background-image':'url(' +squareUrl+')', 'background-size': '100%'}"
                 @click="callLogin"></el-avatar>
      <template #dropdown style="top: 7vh">
        <el-dropdown-menu>
          <router-link to="/profile">
            <el-dropdown-item>个人门户</el-dropdown-item>
          </router-link>
          <router-link to="/managerfor">
            <el-dropdown-item v-if="isAdmin !== false">管理</el-dropdown-item>
          </router-link>
          <router-link to="/personalMessage">
            <el-dropdown-item>消息列表</el-dropdown-item>
          </router-link>
          <!--          <router-link to="/Info">-->
          <!--            <el-dropdown-item>修改信息</el-dropdown-item>-->
          <!--          </router-link>-->
          <!--          <router-link to="/certificate">-->
          <!--            <el-dropdown-item>认证学者</el-dropdown-item>-->
          <!--            <router-link to="/appeal">-->
          <!--              <el-dropdown-item>申诉</el-dropdown-item>-->
          <!--            </router-link>-->
          <!--          </router-link>-->
          <router-link to="/history">
            <el-dropdown-item>历史记录</el-dropdown-item>
          </router-link>
          <el-dropdown-item divided @click="logout()" style="text-align: center;">
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;登出
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
  <el-dialog v-model="loginFormVisible" center width="30vw" custom-class="radius-dialog">
    <template #title style="width:5vw">
      <img :src="iconBlack" alt="">
    </template>
    <el-form ref="loginForm" :rules="loginRules" :model="loginForm" label-position="left">
      <!--      todo:表单验证-->
      <!--            <el-form-item label="姓名" :label-width="formLabelWidth">
                    <el-input v-model="loginForm.name" autocomplete="off" placeholder="请输入真实姓名"></el-input>
                  </el-form-item>
                  <el-form-item label="机构" :label-width="formLabelWidth">
                    <el-select v-model="loginForm.institute" placeholder="Please select a zone">
                      <el-option label="BUAA" value="BUAA"></el-option>
                      <el-option label="NUAA" value="NUAA"></el-option>
                    </el-select>
                  </el-form-item>-->
      <el-form-item prop="name" style="margin-top: 2.5vh">
        <el-input v-model="loginForm.name" autocomplete="on" name="用户名" placeholder="请输入用户名">
          用户名
        </el-input>
      </el-form-item>
      <el-form-item prop="pwd" style="margin-top: 2.5vh">
        <el-input v-model="loginForm.pwd" type="password" autocomplete="off" name="密码" placeholder="请输入密码">
          密码
        </el-input>
      </el-form-item>
      <el-form-item prop="verify" style="margin-top: 2.5vh">
        <el-input
            ref="verify"
            v-model="loginForm.verify"
            placeholder="请填写验证码"
            style="width:60%;"
        >验证码
        </el-input>
        <div class="code" @click="refreshCode"
             style="float:right;margin-top: 0vh;">
          <security :identify-code="identifyCode" @click="refreshCode"/>
        </div>
      </el-form-item>

    </el-form>
    <template #footer>
      <el-checkbox v-model="isremembered" label="记住密码" size="small" style="margin-top: -0.5vh;"></el-checkbox>
      <div class="dialog-footer">
        <el-button @click="loginFormVisible = false; registerFormVisible=true">注册</el-button>
        <el-button type="primary" @click="login(); "
        >登录
        </el-button
        >
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="registerFormVisible" center width="30vw" custom-class="radius-dialog">
    <template #title style="width:5vw">
      <img :src="iconBlack" alt="">
    </template>
    <el-form ref="registerForm" :model="registerForm" :rules="registerRules" label-position="left">
      <!--            <el-form-item label="姓名" :label-width="formLabelWidth">
                    <el-input v-model="loginForm.name" autocomplete="off" placeholder="请输入真实姓名"></el-input>
                  </el-form-item>
                  <el-form-item label="机构" :label-width="formLabelWidth">
                    <el-select v-model="loginForm.institute" placeholder="Please select a zone">
                      <el-option label="BUAA" value="BUAA"></el-option>
                      <el-option label="NUAA" value="NUAA"></el-option>
                    </el-select>
                  </el-form-item>-->
      <el-form-item prop="name">
        <el-input v-model="registerForm.name" autocomplete="off" name="用户名" placeholder="请输入用户名"
                  style="margin: 1vh 5px;">
          用户名
        </el-input>
      </el-form-item>
      <!--      <el-form-item prop="mail">-->
      <!--        <el-input v-model="registerForm.mail" autocomplete="off" name="邮箱" placeholder="请输入邮箱"-->
      <!--                  style="margin: 1vh 5px;"-->
      <!--        >-->
      <!--          邮箱-->
      <!--        </el-input>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item>
              <el-input
                  ref="verify"
                  v-model="registerForm.verify"
                  placeholder="请填写验证码"
                  style="width:60%; margin: 1vh 0;"
              >验证码
              </el-input>
              <span class="code" @click="sendCode"
                    style="float:right;">
              <el-button>发送验证码</el-button>
              </span>
            </el-form-item>-->
      <el-form-item prop="pwd">
        <el-input v-model="registerForm.pwd" autocomplete="off" type="password" name="密码" placeholder="请输入密码"
                  style="margin: 1vh 5px;">
          设置密码
        </el-input>
      </el-form-item>

      <!--            <md-input v-model="registerForm.institute" autocomplete="off" name="邮箱" placeholder="如北京航空航天大学"
                  >
                    当前所属机构
                  </md-input>-->


      <el-form-item prop="checkpwd">
        <el-input v-model="registerForm.checkpwd" autocomplete="off" type="password" name="密码" placeholder="请确认密码"
                  style="margin: 1vh 5px;">
          确认密码
        </el-input>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="register();">注册</el-button>
        <el-button type="primary" @click="registerFormVisible = false; loginFormVisible=true"
        >返回
        </el-button
        >
      </div>

    </template>
  </el-dialog>
</template>

<script>
import {ref} from "vue";
import MdInput from './MDinput'
import security from "./Security/security";
import {ElMessage} from "element-plus";
import axios from "axios";
import router from "../router";

export default {
  name: "NavigatorMenu",
  components: {
    MdInput,
    security
  },
  data() {
    const validateVerify = (rule, value, callback) => {
      if (value !== this.identifyCode) {
        callback(new Error('验证码错误，请重新输入'))
      } else {
        callback()
      }
    }
    const validatepwd = (rule, value, callback) => {
      if (value !== this.registerForm.pwd) {
        callback(new Error('两次密码输入不一致'))
      } else {
        callback()
      }
    }
    const validatemail = (rule, value, callback) => {
      const myReg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
      if (!myReg.test(value)) {
        callback(new Error('邮箱格式不正确'))
      } else {
        callback()
      }
    }
    return {
      activeIndex: ref(this.$route.path),
      squareUrl: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
      icon: require('../assets/images/iconwhite.svg'),
      iconBlack: require('../assets/images/icon.svg'),
      loginFormVisible: false,
      loginForm: {
        // avatar:'',
        // bio: "string",
        // birthday: "2021-12-18T05:31:29.663Z",
        // codeDate: "2021-12-18T05:31:29.663Z",
        // gender: 0,
        // id: 0,
        // identity: 0,
        // isAdmin: true,
        // loginDate: "2021-12-18T05:31:29.663Z",
        // mail: "string",
        // state: 0,
        name: '',
        mail: '',
        pwd: '',
        verify: '',
      },
      loginRules: {
        /* name: [
           {
             required: true,
             message: '请输入用户名',
             trigger: 'blur',
           },
           {
             min: 3,
             max: 10,
             message: '长度应该在3到10字符之间',
             trigger: 'blur',
           },
         ],
         pwd: [{required: true, trigger: 'blur',}],*/
        verify: [{required: true, trigger: 'blur', validator: validateVerify}]
      },
      registerFormVisible: false,
      registerForm: {
        name: '',
        mail: '',
        pwd: '',
        checkpwd: '',
        verify: ''
      },
      registerRules: {
        name: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur',
        },
          {
            min: 3,
            message: '用户名长度至少为3个字符',
            trigger: 'blur',
          }, {
            max: 10,
            message: '用户名长度不超过10个字符',
            trigger: 'blur',
          }],
        pwd: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur',
        },
          {
            min: 6,
            message: '密码长度至少为6个字符',
            trigger: 'blur',
          }, {
            max: 15,
            message: '密码长度不超过15个字符',
            trigger: 'blur',
          }],
        checkpwd: [{
          required: true,
          trigger: 'blur',
          validator: validatepwd
        },],
        mail: [{required: true, trigger: 'blur', validator: validatemail}],
        verify: [{required: true, trigger: 'blur',}]
      },
      isLogin: false,
      formLabelWidth: '12vw',
      isremembered: false,
      identifyCodes: "1234567890abcd",
      identifyCode: "",
      searchContent: {},
      navColor: '#ffffff',
      navColor1: '#ffd04b',
      searchWord: '',
      baseurl: 'http://124.70.186.113:39245',
      imageUrl: '',
      isAdmin: false,
    }
  },
  created() {
    if (sessionStorage.getItem('id')) {
      this.isLogin = true;
    }
  },
  mounted() {
    this.id = sessionStorage.getItem('id');
    axios.get('/api/user', {params: {userId: this.id}}) ////获取个人信息
        .then(response => {
          console.log(response);
          console.log("test");
          this.squareUrl = this.baseurl + response.data.data.avatar
        })
    document.addEventListener('scroll', this.changeHeader, true)
    $("#navSearch *").hide()
    this.loginForm.name = localStorage.getItem('name')
    this.loginForm.pwd = localStorage.getItem('pwd')
  },
  methods: {
    primarySearch() {
      console.log('search!')
      console.log(this.searchWord)
      var filter = 'all'
      sessionStorage.removeItem('hotField')
      sessionStorage.setItem("hotField", filter)
      router.push(
          {
            path: '/searchResult',
            query: {
              value: this.searchWord
            }
          }
      )
    },
    changeHeader() {
      var header = document.querySelector('header')
      // var headerBox = document.querySelector('.headerBox')

      if (window.pageYOffset >= 15) {
        $("#navSearch *").fadeIn()
        $("#navSearch1").fadeOut()

        header.className = 'changeWhite'
        this.icon = require('../assets/images/icon.svg')
        this.navColor = '#000000'
        // headerBox.className = 'headerBox1'
      } else {
        $("#navSearch *").fadeOut()
        $("#navSearch1").fadeIn()

        header.className = 'headerTrans'
        this.icon = require('../assets/images/iconwhite.svg')
        this.navColor = '#ffffff'
        // headerBox.className = 'headerBox'
      }
    },
    refreshCode() {
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
    },
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode += this.identifyCodes[
            this.randomNum(0, this.identifyCodes.length)
            ];
      }
      // console.log(this.identifyCode);
    },
    sendCode() {
      ElMessage({
        showClose: true,
        message: '验证码发送成功',
        type: 'success',
      })
    },
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min)
    },
    register() {
      //todo:注册
      console.log(this.registerForm);
      this.$refs['registerForm'].validate((valid) => {
        if (valid) {
          axios({
            method: 'post',
            url: '/api/user/register/',
            data: this.registerForm
          }).then(response => {
            // console.log('register success!')
            console.log(response)
            if (response.data.code == 200) {
              this.registerFormVisible = false;
              this.loginFormVisible = true;
              ElMessage({
                showClose: true,
                message: '注册成功',
                type: 'success',
              })
            } else {
              console.log(response.data.msg)
              this.$message({
                message: response.data.msg,
                type: 'warning'
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    callLogin() {
      if (!this.isLogin) {
        this.loginFormVisible = true;
        this.refreshCode()
      }
    },
    login() {
      // todo:和后端交互
      this.$refs['loginForm'].validate((valid) => {
        if (valid) {
          axios({
            method: 'post',
            url: '/api/user/login',
            data: this.loginForm
          }).then(response => {
            console.log('login success!')
            console.log(response)
            if (response.data.code == 200) {
              this.loginFormVisible = false
              ElMessage({
                showClose: true,
                message: '登录成功',
                type: 'success',
              })
              if (this.isremembered) {
                localStorage.setItem("name", this.loginForm.name)
                localStorage.setItem("pwd", this.loginForm.pwd)
              } else {
                localStorage.removeItem("name")
                localStorage.removeItem("pwd")
              }
              sessionStorage.setItem('id', response.data.data.id)
              sessionStorage.setItem('isAdmin', response.data.data.isAdmin)
              sessionStorage.setItem('user', response.data.data)
              this.isAdmin = response.data.data.isAdmin
              console.log(sessionStorage.getItem('id'));
              console.log('前端存储user')
              console.log(sessionStorage.getItem('user'));
              console.log(sessionStorage.getItem('isAdmin'));
              this.squareUrl = this.baseurl + response.data.data.avatar
              console.log(this.squareUrl);
              this.$store.isLogin = true
              this.isLogin = true
            } else {
              console.log(response.data.msg)
              this.$message({
                message: response.data.msg,
                type: 'warning'
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    logout() {
      axios({
        method: 'post',
        url: '/api/user/logout',
        data: {}
      }).then(response => {
        console.log('logout success!')
        console.log(response)
        if (response.data.code == 200) {
          // this.$store.isLogin = false;
          this.isLogin = false;
          this.squareUrl = 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png'
          sessionStorage.removeItem('id')
          sessionStorage.removeItem('user')
          sessionStorage.removeItem('isAdmin')

          ElMessage({
            showClose: true,
            message: '退出成功',
            type: 'success',
          })
          Object.keys(this.loginForm).forEach(key => {
            this.loginForm[key] = ''
          })
        } else {
          console.log(response.data.msg)
          this.$message({
            message: response.data.msg,
            type: 'warning'
          })
        }
        this.$router.push('/')
      }).catch(
          // this.$message({
          //   message: "登出失败，请检查网络状况",
          //   type: 'warning'
          // })
      )

    },

    simpleSearch() {
      const Parameters = {
        key: '主题',
        oprater: '',
        page: 1,
        size: 20,
        value: this.searchWord,
      }
      axios({
        method: 'post',
        url: 'api/paper/simple-search',
        data: Parameters
      }).then(result => {
        console.log(quest)
        if (result.code == 200) {
          this.Papers = result.data.Papers
          this.relatedScholars = result.data.relatedScholars
        } else {
          console.log(result.msg)
          this.$message({
            message: '抱歉，无法访问',
            type: 'warning'
          })
        }
      })
    },
  }
}
</script>

<style scoped>
.headerTrans * {
  background: transparent;
  transition: 1.5s;
  height: 10vh;
  border: none;
  color: white;
  z-index: 50;
  /*background: transparent;*/
}

.headerTrans {

}

.changeWhite {
  color: #131212;
  background: white;
  transition: 1.5s;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  width: 100%;
  height: 10vh;
  position: fixed;
  z-index: 50;
}

.el-menu {
  position: fixed;
  width: 60vw;
  left: 10vw;
  z-index: 60;
  height: 10vh;
}

.el-menu1 > * {
  height: 10vh;
  line-height: 10vh;
  width: 10vw;
  font-size: 1.4vw;
}

</style>
<style lang="scss">
.radius-dialog {
  padding: 5px 15px;
  border-radius: 28px;
  background: rgba(255, 255, 255, 0.9);
  //filter: blur(4px);
}

.md-input {
  background: none;
}

.el-input {
  background: none;
}

.el-menu1 * {
  text-align: center;
}

.showSearch * {
  display: inline-block;
}

.hideSearch * {
  display: none;
}
</style>
